
#include "tme_log.h"

/* 打印头 */
static const char* gTmeLogHead[] = {
    "TME-I",
    "TME-E",
    "TME-D",
    "TME-H",
};

/* linux终端打印颜色 */
static const char* gTmeLogColor[] = {
    "\033[40;32m", /* 黑底,绿字 */
    "\033[40;31m", /* 黑底,红字 */
    "\033[40;33m", /* 黑底,黄字 */
    "\033[40;35m", /* 黑底,紫字 */
};

void tme_log_print(
    int32_t type,
    const char* function,
    int32_t line,
    const char* fmt, ...)
{
    char buff[TME_LOG_ONCE_SIZE] = {0};
    size_t buffLen = 0;

    va_list ap;
    va_start(ap, fmt);
    if (type != TME_LOG_TYPE_HEX)
    {
        buffLen = vsnprintf(buff, sizeof(buff), fmt, ap);
    }
    else
    {
        int hexBuffSize = va_arg(ap, int);
        const uint8_t* hexBuff = (const uint8_t*)fmt;
        uint8_t tmpVal;
        while (hexBuffSize > 0 && buffLen + 3 < TME_LOG_ONCE_SIZE)
        {
            /* 装填3个字符 */
            buff[buffLen++] = ' ';
            tmpVal = (*hexBuff) >> 4;
            buff[buffLen++] = tmpVal > 9 ? (tmpVal - 10 + 'A') : (tmpVal + '0');
            tmpVal = (*hexBuff) & 0x0F;
            buff[buffLen++] = tmpVal > 9 ? (tmpVal - 10 + 'A') : (tmpVal + '0');
            /* 移动源数组 */
            hexBuff += 1;
            hexBuffSize -= 1;
        }
    }
    va_end(ap);

#if(TME_LOG_IN_DEBUG)
    if (buffLen > 0)
#else
    if (buffLen > 0 && type != TME_LOG_TYPE_DEBUG)
#endif
    {
#if defined(WIN32) || defined(WIN64) || defined(WINCE) || defined(_MSC_VER)
/* ----- Windows begin ----- */
#if(TME_LOG_IN_DETAIL)
        fprintf(stderr, "[%s][%s](%d) %s\r\n", gTmeLogHead[type], function, line, buff);
#else
        fprintf(stderr, "[%s] %s\r\n", gTmeLogHead[type], buff);
#endif
/* ----- Windows end ----- */
#else
/* ----- Linux begin ----- */

#if(TME_LOG_IN_DETAIL)
        fprintf(stderr, "%s[%s][%s](%d) %s \033[0m\r\n", gTmeLogColor[type], gTmeLogHead[type], function, line, buff);
#else
        fprintf(stderr, "%s[%s] %s \033[0m\r\n", gTmeLogColor[type], gTmeLogHead[type], buff);
#endif
/* ----- Linux end ----- */
#endif
    }
}
